/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server.registry;

import com.je.connector.base.connection.Connection;
import com.je.connector.base.connection.channel.SocketChannel;
import com.je.connector.base.connection.registry.ConnectionRegistry;
import com.je.connector.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * Netty实现的链接注册器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.connection.impl
 * @ClassName: LocalConnectionRegistry
 * @Description: Netty实现的链接注册器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Slf4j
public class LocalConnectionRegistry implements ConnectionRegistry {

    private static ConcurrentMap<SocketChannel, Connection> CONNECTIONS = new ConcurrentHashMap<>();
    private AtomicInteger status = new AtomicInteger(STATUS_CREATEED);

    @Override
    public boolean exist(Connection connection) {
        return CONNECTIONS.containsKey(connection.getSocketClient());
    }

    @Override
    public Connection get(SocketChannel socketClient) {
        return CONNECTIONS.get(socketClient);
    }

    @Override
    public Connection removeAndClose(SocketChannel socketClient) {
        return CONNECTIONS.remove(socketClient);
    }

    @Override
    public void add(Connection connection) {
        CONNECTIONS.putIfAbsent(connection.getSocketClient(), connection);
    }

    @Override
    public void putUser(Connection connection) {
        if(!exist(connection)){
            throw new ServiceException(String.format("此服务不存在此链接！用户为%s",connection.getUserId()));
        }
        CONNECTIONS.put(connection.getSocketClient(),connection);
    }

    @Override
    public long getConnectionNum() {
        return CONNECTIONS.size();
    }

    @Override
    public void init() {
        if (!status.compareAndSet(STATUS_CREATEED, STATUS_INITED)) {
            throw new ServiceException("connection registry init failure");
        }
    }

    @Override
    public void destroy() {
        if (!status.compareAndSet(STATUS_INITED, STATUS_DESTROY)) {
            throw new ServiceException("connection registry destroy failure");
        }
        CONNECTIONS.values().forEach(Connection::disConnect);
        CONNECTIONS.clear();
    }

    @Override
    public boolean localExist(Connection connection) {
        return CONNECTIONS.containsKey(connection.getSocketClient());
    }

    @Override
    public List<Connection> getLocalConnections() {
        return getConnections();
    }

    @Override
    public List<Connection> getConnections() {
        return CONNECTIONS.values().stream().collect(Collectors.toList());
    }

}
